<?php

namespace addons\News\merchant\controllers;

use Yii;
use common\traits\Curd;
use common\models\base\SearchModel;
use common\enums\StatusEnum;
use yii\data\Pagination;
use addons\News\common\models\News;
use addons\News\common\models\Cate;

class NewsController extends BaseController
{
    use Curd;

    /**
     * @var
     */
    public $modelClass = News::class;


    /**
     * 首页
     *
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'partialMatchAttributes' => ['title'], // 模糊查询
            'defaultOrder' => [
                'sort' => SORT_ASC,
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere(['>=', 'status', StatusEnum::DISABLED])
        ->andFilterWhere(['merchant_id' => Yii::$app->user->identity->merchant_id]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'cates' => Cate::getDropDown()

        ]);
    }
    public function actionCreate()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', null);
        $model = $this->findModel($id);

        if ($model->load($request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }
        return $this->render($this->action->id, [
            'model' => $model,
            'cates' => Cate::getDropDown(),
        ]);
    }
    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', null);
        $model = $this->findModel($id);

        if ($model->load($request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }
        return $this->render($this->action->id, [
            'model' => $model,
            'cates' => Cate::getDropDown(),
        ]);
    }
    /**
     * 详情
     *
     * @param $id
     * @return mixed|string
     */
    public function actionView($id)
    {
        if (empty($id) || empty(($model = News::find()->where([
                'id' => $id,
                'status' => StatusEnum::ENABLED
            ])->one()))) {
            return $this->message('找不到该文章', $this->redirect(['index']), 'error');
        }

        return $this->render('view', [
            'model' => $model,
        ]);
    }

}
